package android.Spider;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class PollSend extends Activity
{
	public static final String s_strQuestionID = "QuestionID";
	public static final String s_strMsg = "Msg";
	public static final String s_strOptionsCount = "Count";
	public static final String s_strOption = "Option";

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
	
		InitializeContentView();

        m_connection.Initialize(this);

        // <InitializeContacts>
        Cursor cursor = managedQuery(Contacts.ContactMethods.CONTENT_URI, ContactListAdapter.PROJECTION, null, null);
        ContactListAdapter contactAdapter = new ContactListAdapter(cursor, this);

        LinearLayout layout = (LinearLayout)findViewById(R.id.AutoCompleteLayout);
        AutoCompleteTextView textOriginal = (AutoCompleteTextView)findViewById(R.id.EtQueryPollTo); 
        m_autocomplete = new AutoCompleteTextView(this)
        {
        	private boolean m_bCompletion = false;

			@Override
			public void performCompletion() {
				m_bCompletion = true;
				super.performCompletion();
				m_bCompletion = false;
			}

			@Override
			protected void replaceText(CharSequence text) {
				if (m_bCompletion)
				{
					String strOldText = getText().toString();
					int nPos = strOldText.lastIndexOf(',') + 1;
					if (nPos < 0)
						nPos = 0;
					
					strOldText = strOldText.substring(0, nPos);
					String newText = strOldText + text;
					text = newText;
				}
				super.replaceText(text);
			}        	
        };
        
        m_autocomplete.setThreshold(1);
        m_autocomplete.setLayoutParams(textOriginal.getLayoutParams());
        layout.addView(m_autocomplete);
        textOriginal.setVisibility(View.GONE);
        
        m_autocomplete.setAdapter(contactAdapter);
        // </InitializeContacts>
        
        if (DoesOptionsExist())
        {
    		Spinner spinner = (Spinner)findViewById(R.id.spinner1);
    		
    		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    this, R.array.options, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
            
    		spinner.setOnItemSelectedListener(m_lsnOnSpinner);

    		OrganizeOptions(2);
        }
        
        Bundle bundle = getIntent().getExtras();
        if (bundle != null)
        	FromBundle(bundle, false);
	}
	
	private void FromBundle(Bundle bundle, boolean bEnable)
	{
    	String strMsg = bundle.getString(s_strMsg);
   		EditText txtMessage = (EditText)findViewById(R.id.EtQueryPollMessage);
   		txtMessage.setText(strMsg);
   		txtMessage.setEnabled(bEnable);
   		
   		int nCount = bundle.getInt(s_strOptionsCount);
   		Spinner spinner = (Spinner)findViewById(R.id.spinner1);
   		spinner.setSelection(nCount - 2);
   		spinner.setEnabled(bEnable);
   		
   		EditText edtOption;
   		for (int i = 0; i < nCount; ++i)
   		{
   			String strOption = bundle.getString(s_strOption + i);
   			edtOption = (EditText)findViewById(idOptions[i]);
   			edtOption.setText(strOption);
   			edtOption.setEnabled(bEnable);
   		}
	}
	
	@Override
	protected void onDestroy() {
		m_connection.Unregister();
		super.onDestroy();
	}

	protected void InitializeContentView() {
		setContentView(R.layout.pollsend);
	}

	protected boolean DoesOptionsExist() {
		return true;
	}
	
	private void OrganizeOptions(int nLastVisible)
	{
		final int idLayout[] = { R.id.EditableQueryOption3, R.id.EditableQueryOption4, R.id.EditableQueryOption5, R.id.EditableQueryOption6 };
		for (int i = 2; i < 6; ++i)
		{
			View v = findViewById(idLayout[i - 2]);
			v.setVisibility(i < nLastVisible ? View.VISIBLE : View.GONE);
		}
	}
	
	AdapterView.OnItemSelectedListener m_lsnOnSpinner = new AdapterView.OnItemSelectedListener()
	{
		@SuppressWarnings("unchecked")
		public void onItemSelected(AdapterView parent, View v, int position, long id)
		{
			int nOptions = position + 2;	// Number of edit views to display
			OrganizeOptions(nOptions);
		}

		@SuppressWarnings("unchecked")
		public void onNothingSelected(AdapterView arg0)
		{
			OrganizeOptions(2);
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    
	    menu.add(0, 0, "Send", R.drawable.submitsend);
	    menu.add(0, 1, "Discard", R.drawable.discard);
	    return true;
	}

	@Override
	public boolean onOptionsItemSelected(Menu.Item item)
	{
	    switch (item.getId())
	    {
	    case 0:
	    	OnSend();
	    	break;
	    case 1:
    		finish();
	    	break;
	    default:
	    	return false;
	    }
	    
	    return true;
	}
	
	private void OnSend()
	{
		assert(m_connection.IsInitialized());
		if (m_connection.IsInitialized())
		{
    		EditText txtMessage = (EditText)findViewById(R.id.EtQueryPollMessage);
    		
    		ArrayList<String> lstOptions = new ArrayList<String>();
    		
    		if (DoesOptionsExist())
    		{
        		EditText edtOption;
        		String strOption;
        		for (int i = 0; i < 6; ++i)
        		{
            		edtOption = (EditText)findViewById(idOptions[i]);
            		strOption = edtOption.getText().toString();
            		if (strOption.length() > 0)
            			lstOptions.add(strOption);
        		}
    		}

    		// Here we should parse this string to include other comma separated contacts.
    		String strText = m_autocomplete.getText().toString(); 
    		String[] lstTos = strText.split(",");
    		
    		ArrayList<String> lstTo = new ArrayList<String>();
    		
    		for (int i = 0; i < lstTos.length; ++i)
    		{
    			lstTos[i].trim();
    			int nBegin = lstTos[i].indexOf("<");
    			int nEnd = lstTos[i].indexOf(">");
    			if (nBegin < nEnd)
    				lstTo.add(lstTos[i].substring(nBegin + 1, nEnd));
    			else
    				lstTo.add(lstTos[i]);
    		}

    		if (getIntent().getExtras() == null)		// We didn't initialized it from outside
    			m_connection.SendQuestion(lstTo, txtMessage.getText().toString(), lstOptions, true);
    		else
    			m_connection.ForwardQuestion(getIntent().getExtras().getLong(s_strQuestionID), lstTo);
    		
    		finish();
		}
		else
		{
			Toast.makeText(this, "Connection not initialized", Toast.LENGTH_SHORT).show();
		}
	}

	private AutoCompleteTextView m_autocomplete = null;
	
	private static final int idOptions[] = { R.id.AnswerEditText1, R.id.AnswerEditText2, R.id.AnswerEditText3, 
		R.id.AnswerEditText4, R.id.AnswerEditText5, R.id.AnswerEditText6 };
	
    XmppConnection m_connection = new XmppConnection() { };
}
